import { defineStore } from 'pinia'
import md5 from 'md5'
import { loginUser, getProfile, registerUser } from '@/api/sys'
import { message } from '@/libs/message'
import { LOGIN_TYPE_OAUTH_NO_REGISTER_CODE } from '@/constants/index'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: {}
  }),
  getters: {},
  actions: {
    setToken(token) {
      this.token = token
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },
    /**
     * 注册
     * @param {*} payload
     */
    async register(payload) {
      const { password } = payload
      return await registerUser({
        ...payload,
        password: password ? md5(password) : ''
      })
    },
    /**
     * 登录
     * @param {*} payload
     */
    async login(payload) {
      const { password } = payload
      const { token = '', code } = await loginUser({
        ...payload,
        password: password ? md5(password) : ''
      })
      // 判断是否为扫码需要注册
      if (code === LOGIN_TYPE_OAUTH_NO_REGISTER_CODE) {
        return code
      }
      this.setToken(token)
      if (token) {
        await this.getUserInfo()
      }
    },
    async getUserInfo() {
      const data = await getProfile()
      this.setUserInfo(data)
      message(
        'success',
        `欢迎回来，${
          data.vipLevel
            ? '尊贵的VIP' + data.vipLevel + '用户' + data.nickname
            : data.nickname
        }`,
        6000
      )
    },
    logout() {
      this.setToken('')
      this.setUserInfo({})
      location.reload()
    }
  },
  // 开启数据缓存
  persist: true
})
